/* pony.c */

#include <stdlib.h>
#include <math.h>

#include "pony.h"
#include "path.h"

PONY pony[NUM_PONIES];

void pony_reset_all(void)
{
  int i;

  for (i = 0; i < NUM_PONIES; i++)
    pony[i].active = 0;  
}

int pony_spawn(void)
{
  int i;

  for (i = 0; i < NUM_PONIES; i++)
    if (! pony[i].active) {
      pony[i].active = 1;
      pony[i].point = 0;
      pony[i].seg = 0;
      pony[i].pos = 0;
      return i;
    }
  return -1;
}

void pony_advance(PONY *pony, PATH *path, int steps)
{
  PATH_POINT *point;
  PATH_SEGMENT *seg;

  point = path->points + pony->point;
  seg = point->segs + pony->seg;

  if (point->num_segs <= 0) {
    pony->active = 0;
    return;
  }

  pony->pos += steps;
  while (pony->pos >= seg->steps) {
    pony->pos -= seg->steps;

    /* set new point */
    pony->point = seg->dest_point;
    point = path->points + pony->point;
    if (point->num_segs <= 0) {
      pony->active = 0;
      return;
    }

    /* set new segment */
    pony->seg = rand() % point->num_segs;  /* randomly select segment */
    seg = point->segs + pony->seg;
  }
}

void pony_get_pos(PONY *pony, PATH *path, int *px, int *py, int *pangle)
{
  PATH_POINT *from, *to;
  PATH_SEGMENT *seg;
  double x, y, angle;

  from = path->points + pony->point;
  seg = from->segs + pony->seg;
  to = path->points + seg->dest_point;

  if (seg->steps == 0) {
    *px = *py = *pangle = 0;
    return;
  }

  x = from->x + (to->x - from->x) * (double) pony->pos / seg->steps;
  y = from->y + (to->y - from->y) * (double) pony->pos / seg->steps;
  angle = atan2(to->x - from->x, to->x - from->x);
  while (angle < 0)
    angle += 2. * M_PI;

  *px = (int) x;
  *py = (int) y;
  *pangle = (int) (angle * 180. / M_PI);
}
